package com.leasehold.exception;

import com.leasehold.po.ReturnCode;
import com.leasehold.po.vo.VoData;
import com.leasehold.util.ReturnUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ValidationException;

/**
 * 全局异常处理器
 * 继承HandlerExceptionResolver接口也可以进行全局异常处理，现在不推荐使用
 * ExceptionHandler也可以放到Controller类里面，只处理该Controller里面的异常
 * *@Controller
 * public class XController {
 *
 *     *@ExceptionHandler({NullPointerException.class})
 *     public String exception(NullPointerException e) {
 *         System.out.println(e.getMessage());
 *         e.printStackTrace();
 *         return "null pointer exception";
 *     }
 *
 *     *@RequestMapping("test")
 *     public void test() {
 *         throw new NullPointerException("出错了！");
 *     }
 * }
 * @author fengbo
 * @date 2017/9/28
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public VoData methodArgumentNotValidException(HttpServletRequest request, MethodArgumentNotValidException e) {
        log.error(" ====== Request url is [{}] ====== ", request.getRequestURL(), e);
        return ReturnUtils.fail(ReturnCode.PARAM_INCOMPLETE);
    }

    @ExceptionHandler(ValidationException.class)
    public VoData validationException(HttpServletRequest request, ValidationException e) {
        log.error(" ====== Request url is [{}] ====== ", request.getRequestURL(), e);
        return ReturnUtils.fail(ReturnCode.PARAM_INCOMPLETE);
    }

    @ExceptionHandler(Exception.class)
    public VoData defaultErrorView(HttpServletRequest request, Exception e) {
        log.error(" ====== Request url is [{}] ====== ", request.getRequestURL(), e);
        return ReturnUtils.fail();
    }
}
